import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/mine_charge_coin_page.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/widget/common_dialog.dart';

class SupportUPAlert extends StatefulWidget {
  final bool isPublish;
  final int? selectCoin;
  const SupportUPAlert({super.key, this.isPublish = false, this.selectCoin});

  @override
  State<SupportUPAlert> createState() => _SupportUPAlertState();
}

class _SupportUPAlertState extends State<SupportUPAlert> {
  Rx<int?> selectValue = Rx<int?>(0);
  final textEidtCtr = TextEditingController();
  final focusN = FocusNode();
  final coins = ['10', '20', '30', '40', '50'];
  var enable = false.obs;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      globalStore.refreshWallet().then((value) => checkEnable());
    });
    selectValue.value = widget.selectCoin;
    final contain = coins.contains(widget.selectCoin.toString());
    if (!contain) textEidtCtr.text = widget.selectCoin == null ? '' : widget.selectCoin.toString();
    checkEnable();
  }

  checkEnable() {
    if (widget.isPublish) {
      enable.value = true;
    } else {
      final gold = globalStore.wallet?.amount ?? 0;
      if (gold == 0)
        enable.value = false;
      else {
        final selectCoin = selectValue.value ?? 0;
        if (selectCoin == 0)
          enable.value = true;
        else {
          enable.value = gold >= selectCoin;
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return CommonDialog(
      child: _buildContent(),
    );
  }

  _buildContent() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 60,
          margin: EdgeInsets.symmetric(horizontal: 18),
          height: 6,
          decoration: BoxDecoration(
            color: Color(0x33FFFFFF),
            borderRadius: BorderRadius.circular(4),
          ),
        ),
        20.sizeBoxH,
        Text(
          widget.isPublish ? '设置价格' : '为喜欢的UP主加油',
          style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500),
        ),
        20.sizeBoxH,
        Container(
          padding: EdgeInsets.symmetric(horizontal: 18),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              LayoutBuilder(builder: (_, cons) {
                final width_ = (cons.maxWidth - 48) / 4;
                return Wrap(
                  spacing: 12,
                  runSpacing: 12,
                  children: ['10', '20', '30', '40', '50', '60', '70', '80'].map(
                    (e) {
                      final gold = int.tryParse(e);
                      return Obx(() {
                        final select = gold == (selectValue.value ?? 0);
                        return GestureDetector(
                          onTap: gold == null
                              ? null
                              : () {
                                  selectValue.value = gold;
                                  focusN.unfocus();
                                  textEidtCtr.clear();
                                  checkEnable();
                                },
                          child: Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: (gold != null && select) ? Color(0xffE1351F) : Color(0x0DFFFFFF),
                                borderRadius: BorderRadius.circular(10),
                                border: (gold != null && select)
                                    ? Border.all(color: AppColors.primaryHighColor)
                                    : Border.all(color: Color(0x1AFFFFFF))),
                            width: width_,
                            height: width_ * 1.1,
                            child: () {
                              if (gold != null)
                                return Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Image.asset(
                                      'community_coin.webp'.communityPath,
                                      width: 20,
                                      height: 20,
                                    ),
                                    12.sizeBoxH,
                                    Text(
                                      '$gold金币',
                                      style: TextStyle(color: Color(0x8CFFFFFF), fontSize: 12),
                                    )
                                  ],
                                );
                            }(),
                          ),
                        );
                      });
                    },
                  ).toList(),
                );
              }),
              20.sizeBoxH,
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("自定义", style: TextStyle(color: Color(0x8CFFFFFF))),
                  Container(
                    margin: EdgeInsets.symmetric(horizontal: 5, vertical: 0),
                    width: 60,
                    decoration: BoxDecoration(color: Color(0x33FFFFFF), borderRadius: BorderRadius.circular(6)),
                    child: TextField(
                      controller: textEidtCtr,
                      focusNode: focusN,
                      textAlign: TextAlign.center,
                      onChanged: (value) {
                        selectValue.value = int.tryParse(value);
                        checkEnable();
                      },
                      keyboardType: TextInputType.number,
                      maxLength: 4,
                      inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[0-9]'))],
                      style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        counterText: '',
                        hintText: '100',
                        isDense: true,
                        contentPadding: EdgeInsets.zero,
                        hintStyle: TextStyle(color: Colors.white.withOpacity(.6), fontSize: 12),
                      ),
                    ),
                  ),
                  Text("金币", style: TextStyle(color: Color(0x8CFFFFFF))),
                ],
              ),
              20.sizeBoxH,
              Consumer<GlobalStore>(builder: (_, store, __) {
                // checkEnable();
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (!widget.isPublish) ...[
                      Text(
                        '钱包余额：${store.wallet?.amount ?? 0}',
                        style: TextStyle(color: Colors.white.withOpacity(.6), fontSize: 12, height: 14 / 12),
                      ),
                      16.sizeBoxH,
                    ],
                    Obx(() {
                      // if (store.wallet)
                      if (enable.value)
                        return Row(
                          children: [
                            // Expanded(
                            //   child: GestureDetector(
                            //     onTap: () => Get.back(result: selectValue.value),
                            //     child: Container(
                            //       height: 38,
                            //       alignment: Alignment.center,
                            //       decoration: BoxDecoration(color: Color(0xff16152A), borderRadius: BorderRadius.circular(24)),
                            //       child: Text(
                            //         '稍后再说',
                            //         style: TextStyle(color: Color(0xff989898), fontSize: 14),
                            //       ),
                            //     ),
                            //   ),
                            // ),
                            // 12.sizeBoxW,
                            Expanded(
                              child: GestureDetector(
                                onTap: () => Get.back(result: selectValue.value),
                                child: Container(
                                  height: 54,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Color(0xFFE1351F),
                                  ),
                                  child: Text(
                                    widget.isPublish ? '确定设置' : '立即打赏',
                                    style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w500),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        );
                      return GestureDetector(
                        onTap: () => Get.to(MineChargeCoinPage()),
                        child: Container(
                          height: 38,
                          margin: EdgeInsets.symmetric(horizontal: 20),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(color: AppColors.primaryHighColor, borderRadius: BorderRadius.circular(24)),
                          child: Text(
                            '余额不足 前往充值',
                            style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500),
                          ),
                        ),
                      );
                    }),
                  ],
                );
              })
            ],
          ),
        )
      ],
    );
  }
}
